package com.dayang.redbook.oss.biz.strategy.impl;

import cn.hutool.core.lang.UUID;
import com.dayang.redbook.oss.biz.config.MinioProperties;
import com.dayang.redbook.oss.biz.strategy.FileStrategy;
import io.minio.MinioClient;
import io.minio.PutObjectArgs;
import jakarta.annotation.Resource;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.multipart.MultipartFile;

/**
 * @author: dayang
 * @since: 2024/6/28
 * @description:
 */
@Slf4j
public class MinioFileStrategy implements FileStrategy {
    @Resource
    private MinioProperties minioProperties;

    @Resource
    private MinioClient minioClient;
    @SneakyThrows
    @Override
    public String uploadFile(MultipartFile file, String bucketName) {
        log.info("## 上传文件至 Minio ...");
        if (file == null || file.getSize() == 0){
            log.error("==> 上传文件异常：文件大小为空 ...");
            throw new RuntimeException("文件大小不能为空");
        }

        // 文件原始名称
        String originalFilename = file.getOriginalFilename();
        // 文件contentType
        String contentType = file.getContentType();
        // 随机生成文件名
        String key = UUID.randomUUID().toString(true);
        // 获取文件后缀
        String suffix = originalFilename.substring(originalFilename.lastIndexOf("."));
        String objectName = String.format("%s%s",key,suffix);
        log.info("==> 开始上传文件至 Minio, ObjectName: {}", objectName);

        // 上传文件至minio
        minioClient.putObject(PutObjectArgs.builder()
                .bucket(bucketName)
                .object(objectName)
                .stream(file.getInputStream(), file.getSize(), -1)
                .contentType(contentType)
                .build());
        // 返回文件的访问链接
        String url = String.format("%s/%s/%s", minioProperties.getEndpoint(), bucketName, objectName);
        log.info("==> 上传文件至 Minio 成功，访问路径: {}", url);
        return url;
    }
}
